import _ from "lodash";
import Axios from 'axios';

//日期seconds 格式化为 YY-MM-DD
export function ScondDay(patten) {
  if (!patten) return '';
  let year = new Date(patten).getFullYear();
  let month = new Date(patten).getMonth() + 1;
  let day = new Date(patten).getDate();
  if (month < 10) month = '0' + parseInt(month);
  if (day < 10) day = '0' + parseInt(day);
  return `${year}-${month}-${day}`
}

//日期newDate 格式化为 YY-MM-DD
export function DateDay(patten) {
  if (!patten) return ''
  let year = patten.getFullYear();
  let month = patten.getMonth();
  let day = patten.getDate();
  if (month < 10) month = '0' + parseInt(month);
  if (day < 10) day = '0' + parseInt(day);
  return `${year}-${month}-${day}`
}

//日期newDate 格式化为 09：00
export function Dateformat(patten) {
  if (!patten) return ''
  let hours = patten.getHours();
  let minutes = patten.getMinutes();
  if (hours < 10) hours = '0' + parseInt(hours);
  if (minutes < 10) minutes = '0' + parseInt(minutes);
  return `${hours}：${minutes}`
}

//日期'08:00 - 09:00' 格式化为 [new Date(2019,08,00),new Date(2019,09,00)]
export function GetDate(patten) {
  if (!patten) return '';
  return _.map(patten.split('-'), item => {
    let hours = item.split('：')[0];
    let minutes = item.split('：')[1];
    let years = new Date().getFullYear();
    let month = new Date().getMonth();
    let day = new Date().getDay();
    hours = hours.trim();
    minutes = minutes.trim();
    return new Date(years, month, day, hours, minutes)
  })
}

// 角色格式转换 code - name
// code 必传
// type name类型必传
export function RoleChange(code, type) {
  code = code || '0';
  type = type || 'code';
  code = code.toString();
  let states = [
    {
      code: '0',
      name: '启用'
    },
    {
      code: '-1',
      name: '停用'
    }
  ];
  let names = _.filter(states, item => {
    return item[type] === code;
  }) || states;
  return names;
}

// 图片上传
export function FileChange(e, callback) {
  if (!e) return;
  let file = e.target.files[0];
  if (!file) return;
  let param = new FormData();
  param.append('chunk', '0');
  param.append('chunks', '1');
  param.append('file', file, file.name);
  let config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  };
  Axios.get("/weChat/qiniu/token").then(res => {
    let token = res.data.data;
    param.append('token', token);
    Uploading(param, config, callback);
    return;
  })
}

function Uploading(param, config, callback) {
  Axios.post('http://upload-z1.qiniup.com/', param, config).then(res => {
    let params = {
      message: 'ok',
      url: `http://qiniu1.tianyalei.com/${res.data.key}`
    }
    if (callback) callback(params)
  }).catch(err => {
    console.log(err, 'pppp')
  })
}
